<template>
    <div>
        <!-- 打印管理弹框 -->
        <el-dialog :close-on-click-modal="false"  width="771px" title="打印管理" :visible.sync="show_carList">
            <el-form class="demo-form-inline" size="small">
                <el-form-item label="选择标签样式">
                    <el-radio v-model="printerForm.style_type" label="1" @change="styleTypeChange">小标签</el-radio>
                    <el-radio v-model="printerForm.style_type" label="2" @change="styleTypeChange">大标签</el-radio>
                    <el-radio v-model="printerForm.style_type" label="3" @change="styleTypeChange">条形码</el-radio>
                </el-form-item>
                <el-form-item label="选择打印机">
                    <el-select placeholder="请先选择打印机" v-model="printerForm.id">
                        <el-option v-for="item in printer_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-table  highlight-current-row :data="carList" border>
                <el-table-column align="center" label="图片" width="70">
                    <template slot-scope="scope">
                        <img :src="scope.row.thumb" width="50" height="50" alt="">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="礼品名称" prop="name" width="120"></el-table-column>
                <el-table-column align="center" label="会员兑换票数" prop="ticket_value_vip" width="120"></el-table-column>
                <el-table-column align="center" label="非会员兑换票数" prop="ticket_value" width="120"></el-table-column>
                <el-table-column align="center" label="打印数量" width="100">
                    <template slot-scope="scope">
                        <el-input :disabled="printerForm.style_type!=3" :maxlength="2" onkeypress="return event.which>=48&&event.which<=57"
                            v-model="scope.row.car_gift_num" placeholder="数量"></el-input>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="预览" prop="name" width="100">
                    <template slot-scope="scope">
                        <el-button @click="viewClick(scope.row)" style="font-size:18px" type="text" icon="el-icon-view"></el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="100">
                    <template slot-scope="scope">
                        <el-button @click="delClick(scope.$index)" type="text" style="font-size:18px;color:#f56c6c"
                            icon="el-icon-delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 预览弹框 -->
            <el-dialog :close-on-click-modal="false"  width="540px" style="margin-top:5vh" title="预览样式" :visible.sync="viewDialog" append-to-body>
                <div style="width:300px;margin:0 auto" id="viewPrinter">
                    <p style="text-align: center" v-if="printerForm.style_type==3">
                        <img src="/static/qrcode/barcode.png" alt="">
                        <br> {{viewInfo.no_obsolete}}
                    </p>
                    <div v-else>
                        <p>品名：<span>{{viewInfo.name}}</span></p>
                        <p>售价：<span>{{viewInfo.money_sell}}</span></p>
                        <p>票数：<span>{{viewInfo.ticket_value}}</span></p>
                        <p>货号：<span>{{viewInfo.no_obsolete}}</span></p>
                    </div>
                </div>
            </el-dialog>
            <div class="bottom_box">
                <el-button type="text" size="small" @click="delCarListClick()">清空打印列表</el-button>
                <el-button :loading="in_printer" class="pull-right" size="small" type="primary" @click="sendMessage()">{{in_printer?'打印中':'确认打印'}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        props: ["categoryId", "carList", "list"],
        data() {
            return {
                ws: {},
                viewInfo: {},
                viewDialog: false,
                wsUrl: 'ws://localhost:2012',
                printer_list: [],
                printerForm: {
                    style_type: '',
                    id: '',
                },
                in_printer: false,
                show_carList: false,
            }
        },
        created() {
        },
        methods: {
            subString1(str, len) {
                var regexp = /[^\x00-\xff]/g;// 正在表达式匹配中文
                // 当字符串字节长度小于指定的字节长度时
                if (str.replace(regexp, "aa").length <= len) {
                    return str;
                }
                // 假设指定长度内都是中文
                var m = Math.floor(len / 2);
                for (var i = m, j = str.length; i < j; i++) {
                    // 当截取字符串字节长度满足指定的字节长度
                    if (str.substring(0, i).replace(regexp, "aa").length >= len) {
                        return str.substring(0, i);
                    }
                }
                return str;
            },
            styleTypeChange() {
                this.carList.forEach((val, i) => {
                    val.car_gift_num = this.printerForm.style_type == 3 ? '' : 1
                });
            },
            watch_in_car() {
                this.list.forEach((val1, i1) => {
                    val1.in_car = false
                    this.carList.forEach((val2, i2) => {
                        if (val1.gift_id == val2.gift_id) {
                            val1.in_car = true
                        }
                    });
                });
            },
            showCar() {
                this.printerForm.style_type = '';
                this.printerForm.id = '';
                this.carList.length>0&&this.carList.forEach(val=>{
                    val.car_gift_num="";
                })                
                this.connection();
                this.show_carList = true;
            },
            viewClick(row) {
                if (this.printerForm.style_type == '') {
                    this.$message({ type: 'error', message: '请先选择标签样式再预览' });
                    return;
                }
                this.viewInfo = row;
                this.viewDialog = true;
            },
            // 清空购物车
            delCarListClick() {
                this.carList.splice(0, this.carList.length);
                this.watch_in_car()
            },
            delClick(index) {
                this.carList.splice(index, 1);
                this.watch_in_car()
            },
            connection() {
                const that = this
                if ('WebSocket' in window) {
                    this.ws = new WebSocket(this.wsUrl);
                }
                else if ('MozWebSocket' in window) {
                    this.ws = new MozWebSocket(this.wsUrl);
                } else {
                    alert('当前浏览器不支持');

                }
                //注册各类回调
                this.ws.onopen = function () {
                    that.$message({ type: 'success', message: '连接打印后台成功!' });
                    that.ws.send('B_EnumUSB');
                }
                this.ws.onerror = function () {
                    that.$alert('数据传输发生错误，请连接并运行打印机再试', 'error', { confirmButtonText: '确定', });
                    return;
                }
                this.ws.onmessage = function (receiveMsg) {
                    that.printer_list = [];
                    console.log(that.printer_list);
                    if (receiveMsg.data.split("|")[0] == "B_EnumUSB") {
                        let arr = receiveMsg.data.split("|")
                        arr.splice(0, 1);
                        if (arr.length == 1 && arr[0] == '') {
                            that.$alert('无法枚举到打印机，请确认打印机已经连上电脑', 'error', { confirmButtonText: '确定', });
                            return;
                        }
                        arr.forEach(function (val, i) {
                            that.printer_list.push({
                                id: i + 1,
                                name: val.split("__")[0]
                            })
                        });
                    }
                    if (receiveMsg.data.split("|")[0] == "B_GetPrinterStatus") {
                        switch (receiveMsg.data.split("|")[1]) {
                            case '0':
                                that.in_printer = false;
                                that.$message({ type: 'success', message: '打印完成' });
                                break;
                            case '1':
                                that.$message({ type: 'error', message: '打印命令错误' });
                                break;
                            case '2':
                                that.$message({ type: 'error', message: 'USB端口开启失败' });
                                break;
                            case '3':
                                that.$message({ type: 'error', message: '条码格式错误' });
                                break;
                            case '4':
                                that.$message({ type: 'error', message: '内存溢出' });
                                break;
                            case '6':
                                that.$message({ type: 'error', message: '串口通信异常' });
                                break;
                            case '7':
                                that.$message({ type: 'error', message: '纸张/碳带用完' });
                                break;
                            case '12':
                                that.$message({ type: 'error', message: '打印机暂停' });
                                break;
                            case '50':
                                that.$message({ type: 'error', message: '打印机忙碌' });
                                break;
                        }
                    }
                }
                this.ws.onclose = function () {
                    that.$alert('与打印后台断开连接', 'error', { confirmButtonText: '确定', });
                    // alert('与打印后台断开连接');
                }
            },
            sendMessage() {
                let num_ok = true;
                if (!this.printerForm.style_type || !this.printerForm.id) {
                    this.$message({ type: 'error', message: '请先选择标签样式和打印机' });
                    return;
                }
                this.carList.forEach(function (val, i) {
                    if (val.car_gift_num * 1 <= 0) {
                        this.$message({ type: 'error', message: '请输入打印数量' });
                        num_ok = false;
                        return false;
                    }
                }, this);
                if (this.carList.length == 0) { num_ok = false; this.$message({ type: 'error', message: '无礼品' }); }
                if (!num_ok) { return }
                this.in_printer = true;
                for (let j = 0; j < this.carList.length; j++) {
                    let y = 0;
                    let x = 0;
                    let new_name_x = 0;
                    let new_name_y = 0;
                    let name_more_y = 0;
                    let new_name_more_x = 710;
                    let name_len = 0;
                    let new_name = '';
                    let new_name_more_len = 0;
                    let new_name_more = '';
                    let no_obsolete_len = 0;
                    let no_obsolete_x = 0;
                    let ticket_value_len = 0;
                    let ticket_value_x = 0;
                    let money_sell_len = 0;
                    let money_sell_x = 0;
                    this.ws.send('B_EnumUSB');
                    this.ws.send(`B_CreateUSBPort|${this.printerForm.id}`);
                    for (let i = 0; i < this.carList[j].car_gift_num; i++) {
                        switch (this.printerForm.style_type) {
                            case '1':
                                no_obsolete_len = this.carList[j].no_obsolete.replace(/[^\x00-\xff]/g, "aa").length;
                                no_obsolete_x = (710 - (no_obsolete_len * 10)) / 2

                                ticket_value_len = this.carList[j].ticket_value.replace(/[^\x00-\xff]/g, "aa").length;
                                ticket_value_x = (710 - (ticket_value_len * 10)) / 2

                                money_sell_len = (this.carList[j].money_sell + '').replace(/[^\x00-\xff]/g, "aa").length;
                                money_sell_x = (710 - (money_sell_len * 10)) / 2

                                name_len = this.carList[j].name.replace(/[^\x00-\xff]/g, "aa").length;
                                console.log(name_len)
                                if (name_len > 26) {
                                    new_name_more_len = name_len - 26;
                                    new_name_more_x = (710 - (new_name_more_len * 10)) / 2
                                    new_name = this.subString1(this.carList[j].name, 26)
                                    new_name_more = this.carList[j].name.split(new_name)[1];
                                    name_len = 26;
                                    new_name_y = 140 + 30;
                                    name_more_y = 140;
                                    new_name_x = (580 - (name_len * 10)) / 2;
                                    console.log('名字', new_name)
                                    console.log('多出来的名字', new_name_more)
                                } else {
                                    new_name_y = 140;
                                    name_more_y = 0;
                                    new_name = this.carList[j].name;
                                    new_name_x = (680 - (name_len * 10)) / 2
                                }
                                this.ws.send(`B_Prn_Text_TrueType|${no_obsolete_x}|${15}|30|黑体|3|500|0|0|0|a|${this.carList[j].no_obsolete}`)
                                this.ws.send(`B_Prn_Text_TrueType|${ticket_value_x}|${50}|30|黑体|3|700|0|0|0|b|${this.carList[j].ticket_value}`)
                                this.ws.send(`B_Prn_Text_TrueType|${money_sell_x}|${95}|30|黑体|3|500|0|0|0|c|${this.carList[j].money_sell}`)
                                this.ws.send(`B_Prn_Text_TrueType|${new_name_x}|${new_name_y}|30|黑体|3|200|0|0|0|d|${new_name}`)
                                this.ws.send(`B_Prn_Text_TrueType|${new_name_more_x}|${name_more_y}|30|黑体|3|200|0|0|0|e|${new_name_more}`)
                                break;
                            case '2':
                                no_obsolete_len = this.carList[j].no_obsolete.replace(/[^\x00-\xff]/g, "aa").length;
                                no_obsolete_x = (710 - (no_obsolete_len * 20)) / 2

                                ticket_value_len = this.carList[j].ticket_value.replace(/[^\x00-\xff]/g, "aa").length;
                                ticket_value_x = (710 - (ticket_value_len * 20 * 3)) / 2

                                money_sell_len = (this.carList[j].money_sell + '').replace(/[^\x00-\xff]/g, "aa").length;
                                money_sell_x = (710 - (money_sell_len * 20)) / 2

                                name_len = this.carList[j].name.replace(/[^\x00-\xff]/g, "aa").length;
                                if (name_len > 26) {
                                    new_name_more_len = name_len - 26;
                                    new_name_more_x = (710 - (new_name_more_len * 20)) / 2
                                    new_name = this.subString1(this.carList[j].name, 26)
                                    new_name_more = this.carList[j].name.split(new_name)[1];
                                    name_len = 26;
                                    new_name_y = 365 + 50;
                                    name_more_y = 365;
                                    new_name_x = (660 - (name_len * 20)) / 2
                                    console.log('名字', new_name)
                                    console.log('多出来的名字', new_name_more)
                                } else {
                                    new_name_y = 365;
                                    name_more_y = 0;
                                    new_name = this.carList[j].name
                                    new_name_x = (710 - (name_len * 20)) / 2
                                }

                                console.log('no_obsolete_len', no_obsolete_len)
                                console.log('ticket_value_x', ticket_value_x)
                                console.log('money_sell_x', money_sell_x)
                                console.log('name_len', name_len)
                                this.ws.send(`B_Prn_Text_TrueType|${no_obsolete_x}|${42}|50|仿宋|3|500|0|0|0|a|${this.carList[j].no_obsolete}`)
                                this.ws.send(`B_Prn_Text_TrueType|${ticket_value_x}|${100}|150|仿宋|3|700|0|0|0|b|${this.carList[j].ticket_value}`)
                                this.ws.send(`B_Prn_Text_TrueType|${money_sell_x}|${290}|50|仿宋|3|500|0|0|0|c|${this.carList[j].money_sell}`)
                                this.ws.send(`B_Prn_Text_TrueType|${new_name_x}|${new_name_y}|50|黑体|3|200|0|0|0|d|${new_name}`)
                                this.ws.send(`B_Prn_Text_TrueType|${new_name_more_x}|${name_more_y}|50|黑体|3|200|0|0|0|e|${new_name_more}`)
                                break;
                            case '3':
                                console.log(this.carList[j])

                                y = parseInt(i / 3);
                                x = x == 3 ? 0 : x;
                                name_len = this.carList[j].name.replace(/[^\x00-\xff]/g, "aa").length;
                                new_name = name_len > 18 ? this.subString1(this.carList[j].name, 18) : this.carList[j].name;
                                console.log(`条形码x = ${20 + x * 270}`);
                                console.log(`条形码y = ${30 + y * 210}`);
                                this.ws.send(`B_Prn_Barcode|${20 + x * 270}|${10 + y * 210}|0|1|2|10|100|B|${this.carList[j].no_obsolete}`)
                                this.ws.send(`B_Prn_Text_TrueType|${20 + x * 270}|${150 + y * 210}|25|宋体|1|200|0|0|0|CC|${new_name}`)
                                x++
                                break;
                        }
                    }
                    this.ws.send('B_Print_Out|1');
                    this.ws.send('B_ClosePrn');
                }
                this.ws.send('B_GetPrinterStatus');
            },
        }
    };
</script>
<style rel="stylesheet/scss" lang="scss">
    #viewPrinter span {
        border-bottom: 1px solid #eee;
        display: inline-block;
        width: 200px;
        text-align: center
    }
</style>